package api;

import model.Album;
import model.DBUtil;
import model.Story;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/api/album-editor.json")
public class AlbumEditorApi extends AbsApiServlet {
    @Override
    protected Object doGetInner(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, APIException {
        User currentUser = (User) req.getSession().getAttribute("currentUser");
        if (currentUser == null) {
            throw new APIException("用户先登录");
        }
        int aid = Integer.parseInt(req.getParameter("aid"));
        Album album = new Album();
        album.storyList = new ArrayList<>();
            try (Connection c = DBUtil.getConnection()) {
                {
                    String sql =  "SELECT uid, name, cover FROM album WHERE aid = ?";
                    try (PreparedStatement s = c.prepareStatement(sql)) {
                        s.setInt(1, aid);
                        try (ResultSet rs = s.executeQuery()) {
                            if (!rs.next()) {
                                throw new APIException("adi对应专辑不存在");
                            }
                           int uid = rs.getInt("uid");
                            if (uid != currentUser.uid)
                            {
                                throw new APIException("必须作者更改");
                            }
                            album.aid=aid;
                            album.name = rs.getString("name");
                            album.cover=rs.getString("cover");
                        }
                    }
                }
                {
                    String sql =  "SELECT sid, name FROM story WHERE aid = ? ORDER BY sid";
                    try (PreparedStatement s = c.prepareStatement(sql)){
                        s.setInt(1,aid);
                        try(ResultSet rs = s.executeQuery()){
                            while(rs.next()){
                                Story story = new Story();
                                story.sid = rs.getInt("sid");
                                story.name = rs.getString("name");
                                album.storyList.add(story);
                            }
                        }
                    }
                }
            }
            return album;
    }
}
